﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using WPFDiagramming.Designer;
using WPFDiagramming.Controls;

namespace WPFDiagramming.Toolbox.Adorners
{
    public class SelectConnectorAdorner : Adorner
    {
        private UIElement Source;
        private UIElement Destine;

        private Point _lastMouseClick;

        public Pen Pen { get; set; }

        public SelectConnectorAdorner(UIElement element)
            : base(element)
        {
            if (this.AdornedElement is DiagramPanel)
                ((DiagramPanel)this.AdornedElement).Selected += ElementSelected;
            Pen = new Pen();
            Pen.Brush = Brushes.Black;
        }

        protected void ElementSelected(object sender, RoutedEventArgs e)
        {
            Point position = Mouse.GetPosition(e.Source as UIElement);

            if (this.Source == null)
            {
                this.Source = e.Source as UIElement;
                _lastMouseClick = position;

                this.AdornedElement.MouseMove += ElementMouseMove;
            }
            else
                this.Destine = e.Source as UIElement;

            if (this.Source != null && this.Destine != null)
            {
                Connector c = new Connector((Entity)this.Source, (Entity)this.Destine, _lastMouseClick, position);
                ((Canvas)this.AdornedElement).Children.Add(c);

                this.AdornedElement.MouseMove -= ElementMouseMove;
                ((DiagramPanel)this.AdornedElement).Selected -= ElementSelected;

                this.InvalidateVisual();
            }
        }

        private Geometry GetGeometry()
        {
            Entity source = this.Source as Entity;

            Point startpoint = this._lastMouseClick;

            startpoint.X += source.Left;
            startpoint.Y += source.Top;

            Point endpoint = Mouse.GetPosition(this.AdornedElement);

            PointOrientation startX = PointOrientation.Left;

            if (startpoint.X > (source.Width / 2))
                startX = PointOrientation.Right;

            ConnectorDesigner designer = new ConnectorDesigner(startpoint, startX, endpoint, null);

            return designer.Draw();
        }

        protected void ElementMouseMove(object sender, MouseEventArgs e)
        {
            base.OnMouseMove(e);

            this.InvalidateVisual();
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);
            if (this.Source != null && this.Destine == null)
            {
                drawingContext.DrawGeometry(null, this.Pen, this.GetGeometry());
            }
        }
    }
}
